package com.lanou3g.temp;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "upLoadServlet",urlPatterns ="/upload" )
public class upLoadServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        if (!ServletFileUpload.isMultipartContent(request)) {
            return;
        }
        FileItemFactory factory = new DiskFileItemFactory();
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setHeaderEncoding("utf-8");
        String path =getServletContext().getRealPath("")+File.separator+"upload";
        File uploadDir =new File(path);
        if (!uploadDir.exists()){
            uploadDir.mkdirs();
        }
        try {
            List<FileItem>fileItems =upload.parseRequest(request);
            for (FileItem fileItem : fileItems) {
                String fileName =new File(fileItem.getFieldName()).getName();
                String filePath =path+File.separator+fileName;
                File file =new File(filePath);
                fileItem.write(file);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
